package com.wei.news.ui.activity;


import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wei.base.base.BaseActivity;
import com.wei.base.base.BasePresenter;
import com.wei.base.utils.DialogUtils;
import com.wei.news.App;
import com.wei.news.R;
import com.wei.news.dao.NewBeanDao;
import com.wei.news.model.BaseBean;
import com.wei.news.model.NewBean;

import org.greenrobot.eventbus.EventBus;

import butterknife.Bind;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者：赵若位
 * 时间：2018/5/4 12:16
 * 邮箱：1070138445@qq.com
 * 功能：
 */

public class WebViewActivity extends BaseActivity
{
    @Bind(R.id.tv_title)
    TextView mTvTitle;
    @Bind(R.id.layout)
    RelativeLayout mLayout;
    @Bind(R.id.img_collection)
    ImageView mImgCollection;

    private WebView mWebView;

    private NewBean mData = null;


    @Override
    protected BasePresenter createPresenter()
    {
        return null;
    }

    @Override
    protected int getResourceId()
    {
        return R.layout.activity_web;
    }


    @Override
    public void initView(Bundle savedInstanceState)
    {
        super.initView(savedInstanceState);
        mData = getIntent().getParcelableExtra(this.getClass().getSimpleName());
        //标题
        mTvTitle.setText(mData == null ? "" : mData.getCategory());
        //是否被收藏
        mImgCollection.setImageResource(isCollection() ? R.drawable.icon_collection_2 : R.drawable.icon_collection_1);
        LinearLayout.LayoutParams mParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        mWebView = new WebView(this.getApplicationContext());
        mWebView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setLayoutParams(mParams);
        mLayout.addView(mWebView);

        mWebView.setWebViewClient(new WebViewClient()
        {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String urls)
            {
                view.loadUrl(urls);
                return true;
            }
        });
        mWebView.loadUrl(mData == null ? "" : mData.getUrl());
        //声明WebSettings子类
        WebSettings webSettings = mWebView.getSettings();
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(false);
        //设置自适应屏幕，两者合用（下面这两个方法合用）
        //将图片调整到适合webview的大小
        webSettings.setUseWideViewPort(true);
        // 缩放至屏幕的大小
        webSettings.setLoadWithOverviewMode(true);

        //缩放操作
        //支持缩放，默认为true。是下面那个的前提。
        webSettings.setSupportZoom(true);
        //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setBuiltInZoomControls(true);
        //隐藏原生的缩放控件
        webSettings.setDisplayZoomControls(false);

        //其他细节操作
        //webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        //支持通过JS打开新窗口
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        //支持自动加载图片
        webSettings.setLoadsImagesAutomatically(true);
        //设置编码格式
        webSettings.setDefaultTextEncodingName("utf-8");

        mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        mWebView.getSettings().setDomStorageEnabled(true);
    }


    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        if (mWebView != null)
        {
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebView.clearHistory();

            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
            mWebView.destroy();
            mWebView = null;
        }
        mData = null;
    }


    @OnClick({R.id.img_finish, R.id.img_collection})
    public void onViewClicked(View view)
    {
        switch (view.getId())
        {
            case R.id.img_finish:
                doFinish();
                break;
            case R.id.img_collection:
               collect();
                break;
            default:
                break;
        }
    }


    /**
     * Determines whether the current entity class is stored
     *
     * @return
     */
    private boolean isCollection()
    {
        if (mData == null)
        {
            return false;
        }
        NewBeanDao dao = App.mSession.getNewBeanDao();
        NewBean data = dao.load(mData.getUniquekey());
        if (data != null)
        {
            return true;
        }
        return false;
    }


    /**
     * Remove or add a collection
     */
    private void collect()
    {
        Observable.just(isCollection())
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>()
                {
                    @Override
                    public void accept(final Boolean aBoolean) throws Exception
                    {
                        DialogUtils.getUtils().showDialog(aBoolean ? getString(R.string.dialog_cancel_collection) : getString(R.string.dialog_add_collection), new DialogUtils.OnItemClickListener()
                        {
                            @Override
                            public void clickOk()
                            {
                                NewBeanDao dao = App.mSession.getNewBeanDao();
                                if (aBoolean)
                                {
                                    dao.delete(mData);
                                } else
                                {
                                    dao.insert(mData);
                                }
                                //是否被收藏
                                mImgCollection.setImageResource(isCollection() ? R.drawable.icon_collection_2 : R.drawable.icon_collection_1);
                                EventBus.getDefault().post(new BaseBean(200));
                            }
                        });
                    }
                });
    }
}
